<template>
  <div class="container">
    <div class="app-container">
      <!--角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true">添加角色</el-button>
      </div>
      <!--放置table组件-->
      <el-table :data="roleList" border>
        <el-table-column type="index" :index="indexMethod" label="序号" width="100"></el-table-column>

        <el-table-column prop="name" label="角色" width="200">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" type="text" v-model="row.editRow.name" size="mini"/>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <!--status:1启用，0不启用-->
        <el-table-column label="启用" width="200">
          <!--v-solt="{row}"-->
          <template v-slot="scope">
            <el-switch v-if="scope.row.isEdit" v-model="scope.row.editRow.state" :active-value="1" :inactive-value="0" size="mini"/>
            <span v-else>{{ scope.row.state === 1 ? '已启用' : scope.row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" type="text" v-model="row.editRow.description" size="mini"/>
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <!--编辑状态-->
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="confirmEdit(row)">确认</el-button>
              <el-button size="mini" @click="cancelEdit(row)">取消</el-button>
            </template>
            <!--非编辑状态-->
            <template v-else>
              <el-button type="text" size="mini" @click="AssignPermissions">分配权限</el-button>
              <el-button type="text" size="mini" @click="editRole(row)">编辑</el-button>
              <el-popconfirm title="确定删除该角色吗？" @confirm="confirmDel(row.id)" >
                <el-button slot="reference"
                           style="margin-left:10px"
                           size="mini"
                           type="text">删除
                </el-button>
              </el-popconfirm>
            </template>

          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <el-pagination
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :current-page="pageParams.page"
          :page-size="pageParams.pagesize"
          :total="pageParams.total">
        </el-pagination>
      </el-row>

    </div>
    <!--放置新增角色弹层-->
    <el-dialog title="新增角色"
               :visible.sync="showDialog"
               width="35%"
               @close="closeAddRole"
    >
      <el-form ref="addRole" label-width="120px" :model="formData" :rules="formRules">
        <el-form-item label="角色名称" prop="name">
          <el-input type="text" v-model="formData.name" autocomplete="off" style="width: 300px" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="formData.state" :active-value="1" :inactive-value="0" size="mini">
          </el-switch>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input type="textarea" v-model="formData.description" style="width: 300px" :rows="3"
                    size="mini"></el-input>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="submitAddRole()">确定</el-button>
              <el-button size="mini" @click="closeAddRole">取消</el-button>
            </el-col>
          </el-row>

        </el-form-item>
      </el-form>
    </el-dialog>
    <!--放置分配权限弹层-->
    <el-dialog title="分配权限" :visible.sync="showPermissionDialog">
      <el-tree :data=permissionData
               :props="defaultProps"
               show-checkbox
               default-expand-all

      ></el-tree>
    </el-dialog>

  </div>
</template>
<script>
import {getRoleList, addRole, updateRole, deleteRole} from "@/api/role";
import {getPermissionList} from "@/api/permission";
import {transLisToTreeData} from "@/utils";


export default {
  name: 'Role',
  data() {
    return {
      roleList: [],
      pageParams: {
        page: 1,//当前页
        pagesize: 5,//每页显示数量
        total: 0,//总数
      },
      showDialog: false,
      showPermissionDialog: false,// 放置权限弹层
      permissionData: [],
      defaultProps: {
        label: "description",
        children: 'children'
      },
      // 表单数据
      formData: {
        name: "",//角色名字
        state: 0,//状态启动
        description: ''//角色描述

      },
      //校验规则
      formRules: {
        name: [{required: true, message: '角色名称不能为空', trigger: 'blur'}],
        description: [{required: true, message: '角色描述不能为空', trigger: 'blur'}]
      }

    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 切换分页获取数据
    handleCurrentChange(newPage) {
      this.pageParams.page = newPage
      console.log(`当前页: ${newPage}`);
      console.log(this.pageParams.page)
      this.getRoleList()
    },
    async getRoleList() {
      const {rows, total} = await getRoleList(this.pageParams)
      this.roleList = rows
      this.pageParams.total = total
      this.roleList.forEach(item => {
        // 针对每个数据定义编辑标志
        // this.$set(目标对象,属性值，初始值),使用set添加的对象具有响应式
        this.$set(item, 'isEdit', false)
        this.$set(item,'editRow',{
          name:item.name,
          state:item.state,
          description:item.description
        })
      })
    },
    // 确认添加角色
    submitAddRole: function () {
      this.$refs.addRole.validate(async (valid) => {
        if (valid) {
          await addRole(this.formData)
          // this.$message.success('新增角色成功')
          this.getRoleList()
          this.closeAddRole()
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    //取消添加角色
    closeAddRole() {
      this.$refs.addRole.resetFields()
      this.showDialog = false
    },
    // 分配权限
    async AssignPermissions() {
      const data = await getPermissionList()
      this.permissionData = transLisToTreeData(data, 0)
      this.showPermissionDialog = true
    },
    // 编辑角色
    editRole(row) {
      row.isEdit = true // 改变行的编辑状态
      //更新缓存数据
      row.editRow.name=row.name
      row.editRow.state=row.state
      row.editRow.description=row.description
    },
    //确认编辑
    async confirmEdit(row){
      console.log(row)
      // alert('确认编辑')
      if(row.editRow.name && row.editRow.description){
        await updateRole({...row.editRow,id:row.id})
        // 更新显示成功，退出编辑状态
        row.isEdit = false // 改变行的编辑状态
        // 直接重新获取角色列表，可能导致多个角色同时编辑时，出现问题，此时可以使用Object.assign()
        // this.getRoleList()
        Object.assign(row,{
          ...row.editRow,
          isEdit: false
        })
      }else{
        this.$message.warning('名称和描述不能为空')
      }
    },
    // 取消编辑
    cancelEdit(row){
      row.isEdit=false
    },
    // 删除部门
    async confirmDel(id){
     await deleteRole(id)
      //如果是当前页最后一个，则需要减少页码
      if(this.roleList.length===1) this.pageParams.page--
      //重新加载列表
      this.getRoleList()

    }
  },
  computed: {
    indexMethod(index) {
      // 当前页数 - 1 * 每页数据条数 + 1

      const page = this.pageParams.page
      const pagesize = this.pageParams.pagesize
      console.log(`当前页: ${page},每页数量:${pagesize},index为:${index}`)
      return (page - 1) * pagesize + 1

    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
